import * as THREE from 'three';
import {Object3D} from "three";

let _scene
let _camera
let _container

let threeRaycaster = new THREE.Raycaster();//光线投射器
let mouse = new THREE.Vector2();//二维向量

let projectiveObj;//定义上次投射到的对象

/**
 * 根据光投射器判断鼠标所在向量方向是否穿过物体
 * @param {*} scene     场景
 * @param {*} camera    相机
 */
function renderRaycasterObj() {
    threeRaycaster.setFromCamera(mouse, _camera);
    let intersects = threeRaycaster.intersectObjects(_scene.children);
    if (intersects.length > 0) {
        let currentProjectiveObjT = intersects[0].object;
        if (projectiveObj != currentProjectiveObjT) {
            if((currentProjectiveObjT instanceof THREE.AxesHelper) || (currentProjectiveObjT instanceof THREE.GridHelper)){
                //穿过的是坐标轴线和网格线
                return null;
            }
            projectiveObj = intersects[0].object;
        }
    } else {
        projectiveObj = null;
    }
    return projectiveObj;
}

/**
 * 添加鼠标点击事件，捕获点击时当前选中的物体
 */
window.addEventListener( 'click', function(){
    event.preventDefault();
    let getBoundingClientRect = _container.getBoundingClientRect()
    mouse.x = ((event.clientX - getBoundingClientRect .left) / _container.offsetWidth) * 2 - 1;
    mouse.y = -((event.clientY - getBoundingClientRect .top) / _container.offsetHeight) * 2 + 1;

    let obj = renderRaycasterObj()

    if (!(obj instanceof Object3D)) {
        return
    }
    console.log('选中元素', obj.name)
    if(obj){
        if(obj.hasChecked){
            obj.hasChecked = false;
            // obj.material.color.set("gray");
        }else{
            obj.hasChecked = true;
            // obj.material.color.set("#dd830d");
        }
    }

}, false );

function init(scene, camera, _dom) {
    _scene = scene
    _camera = camera
    _container = _dom
}

export default {
    renderRaycasterObj,
    init
}